package com.study.ju.web.Filter;

import com.study.ju.web.interceptor.ResettableServletRequestWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * <p>重复调用getInputStream处理</p>
 *
 * @author chentao
 * @version v 0.1 2023/5/29 16:12
 */
@Component
public class HttpServletRequestReplacedFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if(request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            if("POST".equals(httpServletRequest.getMethod().toUpperCase()) && "application/json".equalsIgnoreCase(request.getContentType())){
                requestWrapper = new ResettableServletRequestWrapper((HttpServletRequest) request);
            }
        }

        if(requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);    //替换！
        }
    }

    @Override
    public void destroy() {

    }
}
